package servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

//制作验证码
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 150;
        int heigth = 40;

        //创建一个图片输出流对象
        BufferedImage image = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);

        //美化图片

        //给图片上色
        Graphics g = image.getGraphics();
        g.setColor(Color.PINK);
        g.fillRect(0, 0, width, heigth);

        //给图片的边上色
        g.setColor(Color.BLUE);
        g.clipRect(0, 0, width - 1, heigth - 1);

        //随机生成字母
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        //设置字母的大小
        Font font = new Font("宋体", Font.BOLD, 20);
        //建立输入字符输入流
        StringBuilder stringBuilder = new StringBuilder();
        //循环四次，产生四个字母
        for (int i = 1; i <= 4; i ++) {
            int index = random.nextInt(str.length());
            char ch = str.charAt(index);
            //将随机出来的字符存入建立的字符输入流里面
            stringBuilder.append(ch);

            g.setFont(font);
            g.drawString(ch + "", width / 5 * i, 2 * heigth / 3);
        }

        //将随机出来的字符，转为字符串，并存进session里面
        req.getSession().setAttribute("checkCode", stringBuilder.toString());

        //画线， 干扰正常读取
        for (int i = 1; i <= 10; i ++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);

            int y1 = random.nextInt(heigth);
            int y2 = random.nextInt(heigth);

            g.setColor(Color.GREEN);
            g.drawLine(x1, y1, x2, y2);
        }

        //将图片输出
        ImageIO.write(image, "jpg", resp.getOutputStream());


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
